<?php

namespace app\system\service;

use app\model\Stock;
use app\traits\ServiceTrait;
use app\traits\UserTrait;
use think\helper\Arr;

class StockService
{
    use UserTrait;
    use ServiceTrait;

    /**
     * @param $id
     * @param array $with
     * @return array
     */
    public function read($id, $with = []): array
    {
        return Stock::where(['id' => $id])->with($with)->findOrEmpty()->toArray();
    }

    public function userAssign($id, $data)
    {
        $stockIds = Arr::get($data, 'user_ids');
        try {
            $model = Stock::find($id)->users()->sync($stockIds);
        } catch (\Exception $exception) {
            return [false, $exception->getMessage()];
        }
        return [true, $model];
    }


    public function save(array $params, $adminId = 0): array
    {
        //sn唯一性
        if (Stock::where(['serial_no' => $params['serial_no']])->find()) {
            return [false, '设备编号需要唯一，不能重复'];
        }
        $params['created_by'] = $this->getUid($adminId);

        $model = Stock::create($params);
        //设备关联
        if ($dIds = Arr::get($params, 'dids')) {
            $model->devices()->sync(array_unique($dIds));
        }
        return [true, $model];
    }

    /**
     * 添加用户可分配的角色，过滤管理员
     * @return array|\think\Collection|\think\db\BaseQuery[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAvailableList()
    {
        return Stock::where('id', '>', 1)->select();
    }

    public function getList(?array $params, $select = ['*'], $sample = false)
    {
        $query = Stock::order(['id' => 'desc']);
        if ($name = Arr::get($params, 'name')) {
            $query->where(['name' => $name]);
        }
        if ($serialNo = Arr::get($params, 'serial_no')) {
            $query->where(['serial_no' => $serialNo]);
        }
        if ($grainAmount = Arr::get($params, 'grain_amount')) {
            $query->where(['grain_amount' => $grainAmount]);
        }
        if ($grainPlace = Arr::get($params, 'grain_place')) {
            $query->where(['grain_place' => $grainPlace]);
        }
        if ($grainLevel = Arr::get($params, 'grain_level')) {
            $query->where(['grain_level' => $grainLevel]);
        }
        if ($grainVol = Arr::get($params, 'grain_vol')) {
            $query->where(['grain_vol' => $grainVol]);
        }

        if ($status = Arr::get($params, 'status')) {
            $query->where(['status' => $status]);
        }
        if ($onlieStatus = Arr::get($params, 'online_status')) {
            $query->where(['online_status' => $onlieStatus]);
        }
        $pagination = $query
            ->field($select)
            ->paginate([
                'list_rows' => Arr::get($params, $this->listRowsName('system'), 15),
                'var_page' => 'page',
            ]);
        return $sample ? $pagination->items() : pagination($pagination);
    }


    public function update($id, array $data): array
    {
        $exist = Stock::where(['serial_no' => $data['serial_no']])->find();
        if ($exist && $exist['id'] != $id) {
            return [false, '设备编号已经存在'];
        }
        $model = Stock::where('id', $id)->find();
        //设备关联
        if ($dIds = Arr::get($data, 'dids')) {
            $model->devices()->sync(array_unique($dIds));
            unset($data['dids']);
        }
        $data = array_merge($data, [
            'updated_by' => $this->getUid(),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        return [true, $model->save($data)];
    }

    public function updateSort($data): array
    {
        return [true, Stock::update([
            'sort' => $data['numberValue']
        ], ['id' => Arr::get($data, 'id')])];
    }

    public function changeStatus($data): array
    {
        return [true, Stock::update([
            'status' => $data['status']
        ], ['id' => Arr::get($data, 'id')])];
    }

    /**
     * 删除
     * @param $id
     * @param $adminId
     * @return array
     */
    public function del($id, $adminId = 0)
    {
        $model = Stock::update([
            'deleted_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => $this->getUid($adminId),
        ], ['id' => $id]);
        return [true, $model];
    }
}